package com.xuecheng.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LearningProgressDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.RecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mappers.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.search.api.SearchClient;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 选课记录 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-26
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

        @Autowired
        private SearchClient searchClient;
        @Autowired
        private ContentClient contentClient;
        @Autowired
        private MediaClient mediaClient;

        /**
         * 获取当前课程的学习进度
         *
         * @param coursePubId 课程发布id
         * @return vo
         */
        @Override
        public ResponseResult findByCoursePubId(Long coursePubId) {
                // 设置查询条件
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
                qw.eq(CourseRecord::getCoursePubId, coursePubId);
                // 查询
                CourseRecord courseRecord = this.getOne(qw);
                // 判断是否有课程记录
                if (courseRecord == null) {
                        return ResponseResult.okResult();
                }
                // 存在就对象转换
                CourseRecordVo vo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
                return ResponseResult.okResult(vo);
        }

        /**
         * 保存/更新选课记录
         *
         * @param recordDto {coursePubId，userId}
         * @return {code , message}
         */
        @Override
        public ResponseResult saveRecord(RecordDto recordDto) {
                if (recordDto.getCoursePubId() == null || recordDto.getUserId() == null) {
                        throw new BusinessException(ErrorCode.PARAMSERROR);
                }
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getUserId, recordDto.getUserId());
                qw.eq(CourseRecord::getCoursePubId, recordDto.getCoursePubId());
                CourseRecord courseRecord = this.getOne(qw);
                boolean flag = false;
                if (courseRecord != null) {
                        courseRecord.setPaid(OrdersConstants.PAID);
                        flag = this.updateById(courseRecord);
                } else {
                        // 选课记录不存在 则远程调用搜索服务 查询课程内容 进行设置
                        ResponseResult<CoursePubIndexVo> result = searchClient.findById(recordDto.getCoursePubId());
                        CoursePubIndexVo vo = result.getData();
                        courseRecord = new CourseRecord();
                        courseRecord.setUserId(recordDto.getUserId());
                        courseRecord.setCoursePubId(recordDto.getCoursePubId());
                        courseRecord.setCoursePubName(vo.getName());
                        courseRecord.setCompanyId(vo.getCompanyId());
                        courseRecord.setCourseId(vo.getCourseId());
                        courseRecord.setTeachmode(vo.getTeachmode());
                        courseRecord.setCreateDate(new Date());
                        courseRecord.setPaid(OrdersConstants.PAID);
                        // 保存
                        flag = this.save(courseRecord);
                }
                if (!flag) {
                        throw new BusinessException(ErrorCode.ERROR);
                }
                return ResponseResult.okResult();
        }

        @Override
        public ResponseResult findPlayUrl(Long coursePubId, Long mediaId, Long teachplanId) {
                // 判断课程是否收费
                ResponseResult<CoursePubVo> result = contentClient.findById(coursePubId);
                CoursePubVo coursePubVo = result.getData();
                String charge = coursePubVo.getCharge();
                // 如果是收费课程 需要判断用户是否购买 当前章节是否免费
                if (charge.equals(CourseConstants.CHARGE_YES)) {
                        // 判断章节是否免费
                        ResponseResult<TeachplanVo> teachplanResult = contentClient.findPlanById(teachplanId);
                        TeachplanVo vo = teachplanResult.getData();
                        String preview = vo.getIsPreview();
                        if ("0".equals(preview)) {
                                // 判断用户是否购买了课程 根据用户id 和发布id 查询数据
                                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                                qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
                                qw.eq(CourseRecord::getCoursePubId, coursePubId);
                                CourseRecord courseRecord = this.getOne(qw);
                                // 如果不存在或者paid状态是0 是未支付订单
                                if (ObjectUtil.isEmpty(courseRecord) || courseRecord.getPaid().equals(OrdersConstants.NOT_PAID)) {
                                        throw new BusinessException(ErrorCode.NOTFOUND);
                                }
                        }
                }
                return mediaClient.findMediaUrl(mediaId);
        }

        //保存或者更新选课记录
        @Override
        public ResponseResult progress(LearningProgressDto dto) {
                // 查询选课记录
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
                qw.eq(CourseRecord::getCoursePubId, dto.getCoursePubId());
                CourseRecord courseRecord = this.getOne(qw);

                boolean flag = false;
                // 判断选课记录是否存在
                if (courseRecord != null) {
                        // 更新章节信息
                        courseRecord.setTeachplanId(dto.getTeachPlanId());
                        courseRecord.setTeachplanName(dto.getTeachPlanName());
                        flag = this.updateById(courseRecord);
                } else {
                        // 不存在记录 保存
                        ResponseResult<CoursePubIndexVo> result = searchClient.findById(dto.getCoursePubId());
                        CoursePubIndexVo coursePub = result.getData();
                        // 构造选课数据
                        courseRecord = new CourseRecord();
                        courseRecord.setUserId(AuthInfoHolder.getUserId());
                        courseRecord.setCoursePubId(dto.getCoursePubId());
                        courseRecord.setCoursePubName(coursePub.getName());
                        courseRecord.setCompanyId(coursePub.getCompanyId());
                        courseRecord.setCourseId(coursePub.getCourseId());
                        courseRecord.setTeachmode(coursePub.getTeachmode());
                        courseRecord.setTeachplanId(dto.getTeachPlanId());
                        courseRecord.setTeachplanName(dto.getTeachPlanName());
                        courseRecord.setCreateDate(new Date());
                        courseRecord.setPaid(OrdersConstants.NOT_PAID);
                        //保存
                        flag = this.save(courseRecord);
                }
                if(!flag){
                        throw new BusinessException(ErrorCode.ERROR);
                }
                return ResponseResult.okResult();
        }

        @Override
        public ResponseResult<CourseRecord> myCourses(PageRequest pageRequest) {
                Page<CourseRecord> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
//                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
//                qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
                Page<CourseRecord> recordPage = this.page(page);
                List<CourseRecord> courseRecordList = recordPage.getRecords();
                List<CourseRecordVo> vos = BeanHelper.copyWithCollection(courseRecordList, CourseRecordVo.class);
                return PageResponseResult.okResult(recordPage.getTotal(),vos);
        }
}
